﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace TheOliver.Controls.MemoryControl
{
    public class MemoryControl : UserControl
    {
        DispatcherTimer _timer;
        TextBlock _totalMemory;

        public MemoryControl()
        {
            StackPanel sp = new StackPanel();
            this.Content = sp;

            // Total Memory
            _totalMemory = new TextBlock();
            _totalMemory.Text = "Total Memory";
            sp.Children.Add(_totalMemory);

            _timer = new DispatcherTimer();
            _timer.Interval = new TimeSpan(0, 0, this.UpdateInterval);
            _timer.Tick += _timer_Tick;
            this.Loaded += (s, e) =>
                {
                    UpdateValues();
                    CheckIsEnabled();
                };

            this.IsEnabledChanged += (s, e) =>
                {
                    CheckIsEnabled();
                };
        }

        private void CheckIsEnabled()
        {
            if (this.IsEnabled)
            {
                _timer.Start();
            }
            else
            {
                _timer.Stop();
            }
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            UpdateValues();
        }

        private void UpdateValues()
        {
            long totalMemoryInKb = GC.GetTotalMemory(true) / 1024;
            _totalMemory.Text = totalMemoryInKb.ToString() + " KB";
        }

        public int UpdateInterval
        {
            get { return (int)GetValue(UpdateIntervalProperty); }
            set { SetValue(UpdateIntervalProperty, value); }
        }

        // Using a DependencyProperty as the backing store for UpdateInterval.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UpdateIntervalProperty =
            DependencyProperty.Register(
                "UpdateInterval", 
                typeof(int), 
                typeof(MemoryControl), 
                new PropertyMetadata(5, OnUpdateIntervalChanged));

        static void OnUpdateIntervalChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            MemoryControl mc = sender as MemoryControl;
            mc._timer.Stop();
            mc._timer.Interval = new TimeSpan(0, 0, (int)args.NewValue);
            mc.CheckIsEnabled();
        }

    }
}
